<template>
  <div>
    <page-container title="重置密码">
      <template #form>
        <el-form
          label-width="120px"
          ref="passwordFormRef"
          :rules="passwordFormRules"
          :model="formData"
          v-loading="loading">
          <el-form-item label="原密码" prop="old_pwd">
            <el-input v-model="formData.old_pwd" />
          </el-form-item>
          <el-form-item label="新密码" prop="new_pwd">
            <el-input v-model="formData.new_pwd" />
          </el-form-item>
          <el-form-item label="确认密码" prop="re_pwd">
            <el-input v-model="formData.re_pwd" />
          </el-form-item>
          <el-form-item>
            <el-button
              @click="onSubmit"
              style="background-color: #1c332a; color: #fff"
              >修改密码</el-button
            >
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </template>
    </page-container>
    {{ counter.count }}
    <el-button @click="counter.addCount()">+1</el-button>
  </div>
</template>
<script setup>
import { ref } from 'vue';
const formData = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
});
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('密码不能为空'));
  } else if (value !== formData.value.new_pwd) {
    callback(new Error('两次密码输入不一致'));
  } else {
    callback();
  }
};
const passwordFormRules = {
  old_pwd: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    {
      pattern: /^\S{3,15}/,
      message: '请输入3-15位的非空字符',
      trigger: 'blur'
    }
  ],
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      pattern: /^\S{3,15}/,
      message: '请输入3-15位的非空字符',
      trigger: 'blur'
    }
  ],
  re_pwd: [{ validator: validatePass2, trigger: 'blur' }]
};
const passwordFormRef = ref(null);
const loading = ref(false);
import { updateUserPasswordApi } from '@/api/user.js';
const onSubmit = async () => {
  passwordFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      loading.value = false;

      const res = await updateUserPasswordApi(formData.value);
      if (res.code == 0) {
        ElMessage.success(res.message);
        console.log(res, 'res');
      } else if (res.code == 1) {
        ElMessage.error('旧密码错误!');
      } else {
        ElMessage.error(res.message);
      }
    } else {
    }
  });
};
const onReset = () => {
  passwordFormRef.value.resetFields();
};

import { useCounterStore } from '@/stores/modules/count';
const counter = useCounterStore();
</script>
<style lang="less" scoped>
.el-input {
  width: 30%;
}
</style>
